package client;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;

public class TestClient {

	public static void main(String[] args) {
		Properties properties = new Properties();
		try {
			InputStream inputStream = TestClient.class.getClassLoader().getResourceAsStream("config.properties");
			properties.load(inputStream);
			inputStream.close();

			String restUrl = properties.getProperty("RESTURL");
			String sysId = properties.getProperty("SYSID");
			String appSubId = properties.getProperty("APPSUBID");
			String appPubId = properties.getProperty("APPPUBID");
			String partnerId = properties.getProperty("PARTNERID");
			String apiId = properties.getProperty("APIID");
			String formatterStr = properties.getProperty("FORMATTER");
			String appToken = properties.getProperty("APPTOKEN");
			String appAppSecret = properties.getProperty("APPAPPSECRET");
			String format = properties.getProperty("FORMAT");
			String signMethod = properties.getProperty("SIGNMETHOD");
			String apiVersion = properties.getProperty("APIVERSION");

			JSONObject configJson = new JSONObject();
			configJson.put("App_Sub_ID", appSubId);
			configJson.put("App_Pub_ID", appPubId);
			configJson.put("Partner_ID", partnerId);
			configJson.put("Sys_ID", sysId);
			configJson.put("Api_ID", apiId);
			configJson.put("App_Token", appToken);
			configJson.put("Format", format);
			configJson.put("Sign_Method", signMethod);
			configJson.put("Api_Version", apiVersion);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", "111");
			
			String requestData = JSON.toJSONString(map);
			
			SimpleDateFormat formatter = new SimpleDateFormat(formatterStr);
			String timeStamp = formatter.format(new Date());
			configJson.put("Time_Stamp", timeStamp);
			String sign = sign(configJson,appAppSecret);
			configJson.put("Sign", sign);

			JSONObject rootJsonObject = new JSONObject();
			rootJsonObject.put("REQUEST_DATA", new JSONObject(requestData));
			rootJsonObject.put("HRT_ATTRS", configJson);
			JSONObject requestJsonObject = new JSONObject();
			requestJsonObject.put("REQUEST", rootJsonObject);
			String responseData = doTestJson(restUrl, requestJsonObject.toString());
			System.out.println(responseData);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	@SuppressWarnings("rawtypes")
	public static String sign(JSONObject jsonObject, String appAppSecret) {
		String result = null;
		
		Map<String, String> paramMap = new TreeMap<String, String>();
		paramMap.put("App_Token", jsonObject.getString("App_Token"));
		paramMap.put("Api_Version", jsonObject.getString("Api_Version"));
		paramMap.put("App_Sub_ID", jsonObject.getString("App_Sub_ID"));
		paramMap.put("Api_ID", jsonObject.getString("Api_ID"));
		paramMap.put("Sign_Method", jsonObject.getString("Sign_Method"));
		paramMap.put("Time_Stamp", jsonObject.getString("Time_Stamp"));
		paramMap.put("Format", jsonObject.getString("Format"));
		paramMap.put("Sys_ID", jsonObject.getString("Sys_ID"));
		paramMap.put("Partner_ID", jsonObject.getString("Partner_ID"));
		paramMap.put("App_Pub_ID", jsonObject.getString("App_Pub_ID"));
		paramMap.put("REQUEST_DATA", "{}");

		StringBuffer bufferSign = new StringBuffer();
		for (Map.Entry entry : paramMap.entrySet()) {
			bufferSign.append((String) entry.getKey()).append("=")
					.append((String) entry.getValue()).append("&");
		}
		bufferSign.append(appAppSecret);	
		
		try {
			result = DigestUtils.md5Hex(bufferSign.toString().getBytes("UTF-8"))
					.toUpperCase();
		} catch (Exception e) {
		}

		return result;
	}
	
	public static String doTestJson(String url, String json) {
		String result = "";
		HttpClient httpclient = null;
		try {
			httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
			httpPost.setHeader("Accept", "application/json");
			StringEntity stringEntity = new StringEntity(json, Charset.forName("UTF-8"));
			stringEntity.setContentType("application/json");
			httpPost.setEntity(stringEntity);
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "UTF-8");
			}
			httpPost.releaseConnection();
		} catch (Exception e) {
			return e.toString();
		} finally {

		}
		return result;
	}

}
